package com.lvyp.server.controller;

import com.lvyp.server.pojo.Admin;
import com.lvyp.server.pojo.ChatMsg;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 *  聊天室websocket
 */
@Controller
public class WebSocketController {
    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/ws/chat")
    public void handleMsg(Authentication authentication, ChatMsg chatMsg){
        Admin admin = (Admin) authentication.getPrincipal();  // 获取发送者用户信息
        chatMsg.setFrom(admin.getUsername());  // 发送者
        chatMsg.setFromNickName(admin.getName());  // 发送者名称
        chatMsg.setDate(LocalDateTime.now());  // 当前日期
        /**
         * 发送消息
         * 1.消息接收者
         * 2.消息队列
         * 3.消息对象
         */
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(),"/queue/chat",chatMsg);
    }
}
